package com.maddox.relax.dialog;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.core.content.FileProvider;


import com.google.android.material.button.MaterialButton;
import com.maddox.relax.R;
import com.maddox.relax.util.LogUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.FileNameMap;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author View
 */
public class DownLoadDialog extends AlertDialog {
    //高版本路径的Uri,必须声明
    private static final String AUTHORITY="";
    private String loadUrl;
    private String fileName;
    private ProgressBar mProgressbar;
    private MaterialButton btnCancle, btnOpen;
    private LinearLayoutCompat btnContainer;
    private TextView title;
    private String filePath;
    private Context context;
    //如果是下载的app单独判断处理一下
    private boolean isInstallApp = false;


    public DownLoadDialog(@NonNull Context context, String loadUrl, String fileName) {
        this(context, R.style.DownLoadDialogStyle);
        this.loadUrl = loadUrl;
        this.fileName = fileName;
    }

    protected DownLoadDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        this.context = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_download_file);
        checkUri();
        mProgressbar = findViewById(R.id.mprogressBar);
        btnCancle = findViewById(R.id.download_cancle);
        btnOpen = findViewById(R.id.download_open);
        btnContainer = findViewById(R.id.download_btn_container);
        title = findViewById(R.id.title);
        File externalFilesDir = context.getExternalFilesDir(null);
        if (!externalFilesDir.exists()) {
            externalFilesDir.mkdirs();
        }
        filePath = externalFilesDir.getAbsolutePath();
        LogUtil.d("保存路径-->" + filePath);
        setCanceledOnTouchOutside(false);
        setCancelable(false);
        beginDown();
    }

    private void checkUri() {
       if (TextUtils.isEmpty(AUTHORITY)){
           throw new IllegalArgumentException("请设置DownLoadDialog中的uri路径值AUTHORITY属性");
       }
    }

    //更改确定按钮的文本展示
    public void setConfirmBtn(String text) {
        btnOpen.setText(text);
    }

    //判断是否是安装app的下载
    public void setInstallApp(boolean isInstallApp) {
        this.isInstallApp = isInstallApp;
    }


    private void beginDown() {
        new MyDownLoadTask().execute(loadUrl);
    }

    class MyDownLoadTask extends AsyncTask<String, Integer, String> {
        private int currentLength = 0;

        public MyDownLoadTask() {
            super();
        }

        @Override
        protected void onPostExecute(String filePath) {
            title.setText("下载完成");
            if (mProgressbar.getProgress()!=100){
                mProgressbar.setProgress(100);
            }
            btnContainer.setVisibility(View.VISIBLE);
            btnCancle.setOnClickListener(v -> {
                dismiss();
            });
            btnOpen.setOnClickListener(v -> {
                File file = new File(filePath);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri fileUri = null;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    fileUri = FileProvider.getUriForFile(context, AUTHORITY, file);
                } else {
                    fileUri = Uri.fromFile(file);
                }
                FileNameMap fileNameMap = URLConnection.getFileNameMap();
                LogUtil.d("filePath-->" + filePath);
                LogUtil.d("fileUri-->" + fileUri);
                String contentTypeFor = fileNameMap.getContentTypeFor(file.getName());
                LogUtil.d("contentTypeFor-->" + contentTypeFor);
                if (isInstallApp) {
                    intent.setDataAndType(fileUri, "application/vnd.android.package-archive");
                } else {
                    intent.setDataAndType(fileUri, contentTypeFor);
                }
                try {
                    context.startActivity(intent);
                } catch (Exception e) {
                    Toast.makeText(context, "未能找到打开此文件的应用", Toast.LENGTH_SHORT).show();
                }
                dismiss();
            });
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            mProgressbar.setProgress(values[0]);
        }

        @Override
        protected void onCancelled(String s) {
            super.onCancelled(s);
        }

        @Override
        protected String doInBackground(String... strings) {
            InputStream inputStream = null;
            FileOutputStream outputStream = null;
            File outFile = null;
            try {
                URL url = new URL(loadUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.connect();
                int contentLength = connection.getContentLength();
                inputStream = connection.getInputStream();
                outFile = new File(filePath, fileName);
                if (outFile.exists()) {
                    outFile.delete();
                }
                boolean newFile = outFile.createNewFile();
                LogUtil.d("创建文件-->" + newFile);
                outputStream = new FileOutputStream(outFile);
                byte[] bytes = new byte[1024];
                int len = -1;
                while ((len = inputStream.read(bytes)) != -1) {
                    //计算进度
                    currentLength += len;
                    int progress = (int) (((float) (currentLength * 1.0f / contentLength)) * 100);
                    LogUtil.d("当前进度->" + progress);
                    publishProgress(progress);
                    outputStream.write(bytes, 0, len);
                    outputStream.flush();
                }

            } catch (Exception e) {
                e.printStackTrace();
                LogUtil.d("抛出异常-->" + e.getMessage());
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }


            assert outFile != null;
            return outFile.getAbsolutePath();
        }
    }


}
